package cn.yusei.teamTribe.service.team;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.yusei.teamTribe.constant.PermissionType;
import cn.yusei.teamTribe.constant.ResponseCode;
import cn.yusei.teamTribe.dao.team.TeamAlbumDAO;
import cn.yusei.teamTribe.dao.team.TeamPhotoDAO;
import cn.yusei.teamTribe.dao.team.TeamVideoDAO;
import cn.yusei.teamTribe.dao.team.po.TeamAlbumPO;
import cn.yusei.teamTribe.entity.TeamAlbum;
import cn.yusei.teamTribe.exception.TeamPhotoAlbumNotExistsException;
import cn.yusei.teamTribe.service.PermissionService;

@Service
public class TeamAlbumService {

	@Autowired
	private TeamAlbumDAO taDAO;
	@Autowired
	private TeamPhotoDAO tpDAO;
	@Autowired
	private TeamVideoDAO tvDAO;
	@Autowired
	private PermissionService permissionService;
	
	public int add(int userId, TeamAlbum ta) {
		if(!permissionService.havePermission(userId, ta.getTeamId(), PermissionType.UPDATE_TEAM_INFO, 0)) {
			return ResponseCode.PERMISSION_FORBIDDEN;
		}
		if(taDAO.existsName(ta.getTeamId(), ta.getName())) {
			return ResponseCode.ALBUM_ALREADY_EXISTS;
		}
		TeamAlbumPO tpaPO = new TeamAlbumPO();
		BeanUtils.copyProperties(ta, tpaPO);
		taDAO.insert(tpaPO);
		return ResponseCode.REQUEST_SUCCESSED;
	}
	
	public int delete(int userId, int teamId, int albumId) {
		if(!permissionService.havePermission(userId, teamId, PermissionType.UPDATE_TEAM_INFO, 0)) {
			return ResponseCode.PERMISSION_FORBIDDEN;
		}
		if(!taDAO.exists(albumId, teamId)) {
			return ResponseCode.ALBUM_NOT_EXISTS;
		}
		tpDAO.deleteAlbum(teamId, albumId);
		tvDAO.deleteAlbum(teamId, albumId);
		taDAO.delete(albumId, teamId);
		return ResponseCode.REQUEST_SUCCESSED;
	}
	
	public int[] getByTeamId(int teamId) {
		int[] ids = null;
		ids = taDAO.selectByTeamId(teamId);
		return ids;
	}
	
	public TeamAlbum getById(int albumId) throws TeamPhotoAlbumNotExistsException {
		TeamAlbumPO taPO = taDAO.selectById(albumId);
		if(taPO == null) {
			throw new TeamPhotoAlbumNotExistsException();
		}
		TeamAlbum ta = new TeamAlbum();
		BeanUtils.copyProperties(taPO, ta);
		return ta;
	}
	
	public int getLastInsertId() {
		return taDAO.selectLastInsertId();
	}
	
	public int update(int userId, TeamAlbum tpa) {
		if(!permissionService.havePermission(userId, tpa.getTeamId(), PermissionType.UPDATE_TEAM_INFO, 0)) {
			return ResponseCode.PERMISSION_FORBIDDEN;
		}
		if(!taDAO.exists(tpa.getId(), tpa.getTeamId())) {
			return ResponseCode.ALBUM_NOT_EXISTS;
		}
		TeamAlbumPO tpaPO = new TeamAlbumPO();
		BeanUtils.copyProperties(tpa, tpaPO);
		taDAO.update(tpaPO);
		return ResponseCode.REQUEST_SUCCESSED;
	}
}
